<template>
  <div class="traceability-container">
    <!-- 顶部栏 -->
    <div class="header">
      <span>溯源管理</span>
      <el-button icon="el-icon-close" circle class="close-btn"></el-button>
    </div>
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="dialogVisible=true">
        新建
       
      </el-button>
      <el-button
        type="danger"
        
        @click="handleBatchDelete"
      >
        删除
        <el-badge class="badge"/>
      </el-button>
    </div>
    <!-- 数据表格 -->
    <el-table
      :data="pagedData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="50"/>
      <el-table-column type="index" label="序号" width="70"/>
      <el-table-column prop="productName" label="商品名称" min-width="160">
        <template #header>
          商品名称
          <el-input size="small" placeholder="输入进行查询" v-model="filters.productName" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="batch" label="生产批次" min-width="140">
        <template #header>
          生产批次
          <el-input size="small" placeholder="输入进行查询" v-model="filters.batch" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="shelf_life" label="保质期（天）" min-width="120">
        <template #header>
          保质期（天）
          <el-input size="small" placeholder="输入进行查询" v-model="filters.shelf_life" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="license" label="生产许可证号" min-width="160">
        <template #header>
          生产许可证号
          <el-input size="small" placeholder="输入进行查询" v-model="filters.license" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="enterprise" label="生产企业" min-width="160">
        <template #header>
          生产企业
          <el-input size="small" placeholder="输入进行查询" v-model="filters.enterprise" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人" min-width="120">
        <template #header>
          创建人
          <el-input size="small" placeholder="输入进行查询" v-model="filters.createUserName" class="filter-input"/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="160">
        <template #header>
          创建时间
          <el-input size="small" placeholder="输入进行查询" v-model="filters.createTime" class="filter-input"/>
        </template>
        <template #default="{ row }">
          {{ row.createTime ? moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateUserName" label="修改人" min-width="120">
        <template #header>
          修改人
          <el-input size="small" placeholder="输入进行查询" v-model="filters.updateUserName" class="filter-input"/>
        </template>
      </el-table-column>
       <el-table-column prop="updateTime" label="修改时间" min-width="160">
        <template #header>
          修改时间
          <el-input size="small" placeholder="输入进行查询" v-model="filters.updateTime" class="filter-input"/>
        </template>
        <template #default="{ row }">
          {{ row.updateTime ? moment(row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="cover" label="封面图片" width="120">
       <template v-slot="scope">
        <el-image
              :src="scope.row.cover"
              fit="cover"
              style="width: 50px; height: 50px"
            />
       </template>
      </el-table-column>
      <el-table-column prop="integrity" label="信息完整度" width="120">
        <template #default="{ row }">
          <span  :class="getIntegrityClass(row.completeness)" >
            {{ row.completeness }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="340">
        <template #default="scope">
          <el-button  size="small" type="primary" plain @click="Update(scope.row)">修改</el-button>
          <el-button  size="small" type="success" plain>导出溯源码</el-button>
          <el-button
            
            size="small"
            type="danger"
            plain
            @click="handleRowDelete(scope.row.id)"
          >删除</el-button>
          <el-button size="small" type="info" plain @click="goToDetail(scope.row.batch)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="filteredData.length"
      layout="total, first, prev, pager, next, last, jumper"
      :page-sizes="[15]"
      :pager-count="7"
      @current-change="handlePageChange"
    />
    <!-- 添加弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <el-form-item label="商品名称" prop="name">
          <el-select v-model="form.productId" placeholder="请选择商品名称" filterable>
            <el-option
              v-for="item in productOptions"
              :key="item"
              :label="item.productName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input v-model="form.batch" maxlength="30" readonly />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelf_life">
          <el-input
            v-model="form.shelf_life"
            maxlength="5"
            show-word-limit
            placeholder="请输入数字"
            @input="onPeriodInput"
          />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="license">
          <el-input
            v-model="form.license"
            maxlength="30"
            show-word-limit
            placeholder="请输入数字或字母"
            @input="onLicenseInput"
          />
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input
            v-model="form.enterprise"
            maxlength="30"
            show-word-limit
            placeholder="请输入企业名称"
            @input="onCompanyInput"
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <el-upload
    class="avatar-uploader"
    action="http://localhost:5045/api/UpLoad/UpFile"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    v-model="form.cover"
  >
    <img v-if="form.cover" :src="form.cover" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
          <el-button v-if="form.image" size="small" @click="removeImage">删除</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- 修改弹窗 -->
      <el-dialog
      v-model="UndialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <el-form-item label="商品名称" prop="name">
          <el-select v-model="form.productId" placeholder="请选择商品名称" filterable>
            <el-option
              v-for="item in productOptions"
              :key="item"
              :label="item.productName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input v-model="form.batch" maxlength="30" readonly />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelf_life">
          <el-input
            v-model="form.shelf_life"
            maxlength="5"
            show-word-limit
            placeholder="请输入数字"
            @input="onPeriodInput"
          />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="license">
          <el-input
            v-model="form.license"
            maxlength="30"
            show-word-limit
            placeholder="请输入数字或字母"
            @input="onLicenseInput"
          />
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input
            v-model="form.enterprise"
            maxlength="30"
            show-word-limit
            placeholder="请输入企业名称"
            @input="onCompanyInput"
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <el-upload
    class="avatar-uploader"
    action="http://localhost:5045/api/UpLoad/UpFile"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    v-model="form.cover"
  >
    <img v-if="form.cover" :src="form.cover" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
          <el-button v-if="form.image" size="small" @click="removeImage">删除</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="UpdateSave">修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, nextTick, onMounted, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import moment from 'moment'
import { id } from 'element-plus/es/locales.mjs'

const router = useRouter()

const tableData = ref([])
//显示
const seach=()=>
{
  axios.get("http://localhost:5045/api/Traceability/GetTraceabilityShow").then(res=>
  {
    
    tableData.value=res.data.pageData

  })
}
onMounted(()=>
{
  seach()
})
//数据
const filters = ref({
  productName: '',
  batch: '',
  shelf_life: '',
  license: '',
  enterprise: '',
  createUserName: '',
  updateUserName: '',
  createTime: '',
  updateTime: ''
})

const selectedRows = ref([])
//查询
const filteredData = computed(() => {
  return tableData.value.filter(row => {
    // 单字段或多字段（连查）均支持，全部为模糊匹配
    const nameMatch = !filters.value.productName || row.productName.includes(filters.value.productName)
    const batchMatch = !filters.value.batch || String(row.batch).includes(filters.value.batch)
    const periodMatch = !filters.value.shelf_life || String(row.shelf_life).includes(filters.value.shelf_life)
    const licenseMatch = !filters.value.license || row.license.includes(filters.value.license)
    const companyMatch = !filters.value.enterprise || row.enterprise.includes(filters.value.enterprise)
    const creatorMatch = !filters.value.createUserName || row.createUserName.includes(filters.value.createUserName)
    const createTimeMatch = !filters.value.createTime || row.createTime.includes(filters.value.createTime)
    const modifierMatch = !filters.value.updateUserName || row.updateUserName.includes(filters.value.updateUserName)
    // 所有条件都满足才显示
    return nameMatch && batchMatch && periodMatch && licenseMatch && companyMatch &&
      creatorMatch && createTimeMatch && modifierMatch
  })
})

const pageSize = ref(15)
const currentPage = ref(1)
const handlePageChange = (val) => {
  currentPage.value = val
}

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

const getIntegrityClass=(val)=> {
  if (!val || parseFloat(val) < 80.00) return 'integrity-red'
  if (parseFloat(val) === 100.00) return 'integrity-green'
  return 'integrity-red'
}

const handleSelectionChange=(val)=> {
  selectedRows.value = val
}
//批量删除
const handleBatchDelete=(id)=> {
  if (selectedRows.value.length === 0) {
    ElMessageBox.alert('没有选中复选框不能删除', '提示', { type: 'warning' })
    return
  }
  ElMessageBox.confirm('确定要删除选中的数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(item => item.id);
    axios.delete("http://localhost:5045/api/Traceability/Del", {
      params: {
        id: ids.join(",")
      }
    }).then(res => {
      if(res.data.code==200)
      {
        ElMessage.success("删除成功");
        seach();
      }
      else
      {
        ElMessage.error("删除失败");
      }
    })
  })
}
//单删除
function handleRowDelete(id) {
  ElMessageBox.confirm('确定要删除该行数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete("http://localhost:5045/api/Traceability/DeleteProduct",{params:{id:id}}).then(res=>
    {
       if(res.data.code==200)
       {
        ElMessage.success(res.data.message)
        seach()
       }
       else
       {
        ElMessage.error(res.data.message)
       }
    })
    
  })
}

// 商品下拉选项
const productOptions = ref
([

])
const get=()=>
{
  axios.get("http://localhost:5045/api/Traceability/GetProductShow",).then(res=>
  {
    console.log(res.data.data);
    
    productOptions.value=res.data.data
  })
}
onMounted(()=>
{
  get()
})

// 弹窗控制
const dialogVisible = ref(false)
const UndialogVisible = ref(false)

const dialogTitle = ref('新增')
const formRef = ref(null)

// 表单数据
const form = reactive({
  productId: '',
  batch: '',
  shelf_life: '',
  license: '',
  enterprise: '',
  cover: '',
  completeness:'',
  id:''
})

// 校验规则
const rules = {
  productId: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  batch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }],
  shelf_life: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '只能输入数字，最多5位', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{1,30}$/, message: '只能输入数字和字母，最多30位', trigger: 'blur' }
  ],
  enterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9 ]{1,30}$/, message: '仅允许中英文、数字和空格，不能有特殊字符', trigger: 'blur' }
  ],
  cover: [{ required: true, message: '请上传封面图片', trigger: 'change' }]
}

// 标记当前编辑行索引，-1 表示新增
const editIndex = ref(-1)



// 生成唯一生产批次
function generateBatch() {
  const now = new Date()
  const dateStr =
    now.getFullYear().toString() +
    String(now.getMonth() + 1).padStart(2, '0') +
    String(now.getDate()).padStart(2, '0')
  // 生成6位随机字母数字
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let randomStr = ''
  for (let i = 0; i < 6; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return dateStr + randomStr
}

// 保质期只能输入数字
function onPeriodInput(val) {
  form.shelf_life = val.replace(/\D/g, '').slice(0, 5)
}
// 生产许可证号只能输入数字和字母
function onLicenseInput(val) {
  form.license = val.replace(/[^A-Za-z0-9]/g, '').slice(0, 30)
}
// 生产企业只能输入中英文、数字和空格
function onCompanyInput(val) {
  form.enterprise = val.replace(/[^\u4e00-\u9fa5a-zA-Z0-9 ]/g, '').slice(0, 30)
}
const handleAvatarSuccess = (PerObj)=>
{
    form.cover=PerObj
}
const beforeAvatarUpload= (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式错误!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
// 删除图片
function removeImage() {
  form.cover = ''
}

// 保存
function handleSave() {
  formRef.value.validate(valid => {
    if (!valid) return
   
      // 新增
      axios.post("http://localhost:5045/api/Traceability/AddProduct", form).then(res => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.message || '新增成功')
          seach()
          dialogVisible.value = false
        } else {
          ElMessage.error(res.data.message || '新增失败')
        }
      }).catch(err => {
        ElMessage.error('新增失败')
        console.error(err)
      })
    
  })
}
//反填
const Update=(row)=>
{
 UndialogVisible.value=true
 form.productId=row.productId
 form.id=row.id
 form.batch=row.batch
 form.cover=row.cover
 form.license=row.license
 form.shelf_life=row.shelf_life
 form.completeness=row.completeness
 form.enterprise=row.enterprise
}
//修改
const UpdateSave=()=>
{
axios.put("http://localhost:5045/api/Traceability/UpdateProduct",form).then(res=>
{
  if(res.data.code==200)
  {
    ElMessage.success(res.data.message)
    UndialogVisible.value=false
    seach()
  }
  else
  {
    ElMessage.error(res.data.message)
  }
  
})
}

// 重置表单
function resetForm() {
  form.productId = ''
  form.batch = generateBatch()
  form.shelf_life = ''
  form.license = ''
  form.enterprise = ''
  form.cover = ''
}

function goToDetail(Batch) {
  // 可根据row传递参数，如id等，当前跳转到/pls
 
  router.push({ path: '/pls', query: { Batch:Batch } })
}

watch(dialogVisible, (val) => {
  if (val) {
    form.batch = generateBatch()
  }
})
</script>

<style scoped>
.traceability-container { padding: 20px; background: #fff; }
.header { display: flex; justify-content: space-between; align-items: center; font-size: 20px; margin-bottom: 10px; }
.close-btn { float: right; }
.toolbar { margin-bottom: 10px; }
.badge { margin-left: 5px; }
.filter-input { margin-top: 5px; width: 90%; }
.integrity-green { color: #67c23a; font-weight: bold; }
.integrity-orange { color: #e6a23c; font-weight: bold; }
.integrity-red { color: #f56c6c; font-weight: bold; }

/* 图片单元格样式 */
.image-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.table-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.no-image .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #f56c6c;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

/* 表头自动换行样式 */
/deep/ .el-table th .cell {
  white-space: normal !important;
  word-break: break-all;
}